package com.hdu.metrics_center.utils;

import com.hdu.metrics_center.metrics.MetricsExecuteReq;


import java.util.Map;
import java.util.UUID;

import static com.hdu.metrics_center.utils.ParamChecker.unValidParam;
import static java.util.Objects.nonNull;
import static java.util.Optional.ofNullable;

public class RedisCommandBuildUtils {


    private static final String PLACEHOLDER = "#";

    public static MetricsExecuteReq buildMetricsExecuteReq(String keyTemplate,
                                                           String fieldTemplate,
                                                           Map<String, Object> params) {
        String key = placeholdersReplace(keyTemplate, params);
        unValidParam(key.contains(PLACEHOLDER), "占位符参数不够");
        String filed = ofNullable(fieldTemplate).map(fT -> placeholdersReplace(fT, params)).orElse(null);
        unValidParam(nonNull(filed) && filed.contains(PLACEHOLDER), "占位符参数不够");
        return MetricsExecuteReq
                .builder()
                .key(key)
                .field(filed)
                .reqUuid(UUID.randomUUID().toString())
                .build();
    }


    public static String placeholdersReplace(String template, Map<String, Object> params) {
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String keyPattern = keyPattern(entry.getKey());
            if (template.contains(keyPattern)) {
                template = template.replace(keyPattern, entry.getValue().toString());
            }
        }
        return template;
    }

    private static String keyPattern(String key) {
        return PLACEHOLDER + key + PLACEHOLDER;
    }

}
